package com.mrhc.plugin;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import com.device.DeviceCallback;
import com.device.geit.GeitDevice;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

/**
 * Created by qiaoyanqing on 2019/6/21.
 *
 * @link shelljor@sina.com
 */
public class DevicePlugin extends CordovaPlugin {
    public static final String initDevice="initDevice" ;//初始化设备
    public static final String setDeviceName="setDeviceName" ;//设置设备名字
    public static final String conncetDevice="conncetDevice" ;//连接 设备
    public static final String disConnectDevice="disConnectDevice" ;//断开连接
    public static final String readBankCardInfo="readBankCardInfo" ;//读取银行卡基本数据
    public static final String isConnDevice="isConnDevice" ;//检测设备是否连接
    public static final String readIDCardInfo="readIDCardInfo" ;//读取身份证
    public static final String cancelOperation="cancelOperation" ;//取消操作
    public static final String readICCardARQC="readICCardARQC" ;//读取芯片卡ARQC
    public static final String validateARPC="validateARPC" ;//IC卡的ARPC校验。
    public static final String getPin="getPin" ;//读取密码信息
    public static final String getPublicKey="getPublicKey" ;//获取公钥信息
    public static final String loadMainKey="loadMainKey" ;//1.1	主密钥灌注
    public static final String loadWorkKey="loadWorkKey" ;//1.1	工作密钥灌注
    public static final String readFinger="readFinger" ;//读取指纹
    public static final String openSignature="openSignature" ;//1.1	打开签名屏
    public static final String getSignaturePhoto="getSignaturePhoto" ;//获取签名数据
    public static final String clearSignature="clearSignature" ;//清除设备签名屏数据
    public static final String closeSignature="closeSignature" ;//关闭设备签名屏
    public static final String beiyongone="beiyongone" ;//备用标签1
    public static final String beiyongtwo="beiyongtwo" ;//备用标签2




    public static final String show="show" ;// 备用方法，
    public GeitDevice mDevice=new GeitDevice();
    private CallbackContext mCallbackContext;

    @SuppressLint("HandlerLeak")
    Handler mHandler=new Handler(){


        @Override
        public void handleMessage(Message msg) {

            int what = msg.what;
            if (what==4){
                //读取身份证成功
                JSONObject jsonObject= (JSONObject) msg.obj;
                try {
                    Toast.makeText(cordova.getActivity(), "读取成功 姓名"+jsonObject.getString("fullName"), Toast.LENGTH_SHORT).show();
//                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, jsonObject);
//                    mCallbackContext.sendPluginResult(pluginResult);
                    mCallbackContext.success(jsonObject);


                } catch (JSONException e) {
                    Toast.makeText(cordova.getActivity(), "读取失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
                    mCallbackContext.error(e.getMessage());
//                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, e.getMessage());
//                    mCallbackContext.sendPluginResult(pluginResult);

                    e.printStackTrace();
                }

            }else if (what==8){
                String data= (String) msg.obj;
                Toast.makeText(cordova.getActivity(), "读取成功 卡号"+data, Toast.LENGTH_SHORT).show();
                mCallbackContext.success(data);
            }else if (what==14){
                String message=msg.obj.toString();
                Toast.makeText(cordova.getActivity(), "读取失败 ："+message, Toast.LENGTH_SHORT).show();
                mCallbackContext.error(message);
            }else  if (what==15){
                String photo=(String) msg.obj;
                byte[] bt=Base64.decode(photo,Base64.NO_WRAP);
//                iv_signature_data.setImageBitmap(BitmapFactory.decodeByteArray(bt, 0, bt.length));
                mCallbackContext.success(bt);
                Toast.makeText(cordova.getActivity(), "签名操作成功 ："+ Arrays.toString(bt), Toast.LENGTH_SHORT).show();

            }else if ((what==1)){
                String bmp = (String)msg.obj;
                mCallbackContext.success(bmp);
                Toast.makeText(cordova.getActivity(), "指纹操作 ："+ bmp, Toast.LENGTH_SHORT).show();

            }else if (what==3){
                String data=msg.obj.toString();
                mCallbackContext.success(data);
                Toast.makeText(cordova.getActivity(), "读取芯片卡ARQC ："+ data, Toast.LENGTH_SHORT).show();

            }else if (what==7){
                String pwd = (String)msg.obj;
                Toast.makeText(cordova.getActivity(), "读取密码信息 ："+ pwd, Toast.LENGTH_SHORT).show();
                mCallbackContext.success(pwd);

            }



        }
    };


    @Override
    public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {

        mCallbackContext=callbackContext;

        if (action.equals(initDevice)) {

            mDevice.initDevice();
            Log.e("flag","success初始化设备成功");
            callbackContext.success("success初始化设备成功");
            Toast.makeText(cordova.getActivity(), "初始化设备成功", Toast.LENGTH_SHORT).show();
            callbackContext.success("初始化成功");
            return true;

        }else if (action.equals(setDeviceName)){
            Log.e("flag","设备名字"+args.get(0).toString());
            boolean connDevice = mDevice.isConnDevice();
            if (connDevice){
                Log.e("flag","success设备已连接");
                Toast.makeText(cordova.getActivity(), "设备已连接", Toast.LENGTH_SHORT).show();
                Log.e("flag","设备名字"+args.get(0).toString());
                mDevice.setDeviceName(args.get(0).toString());

                Log.e("flag","success setDeviceName设备成功");
                callbackContext.success("success setDeviceName设备成功");
                callbackContext.success("设置名字成功");
                return true;

            }else {
                Toast.makeText(cordova.getActivity(), "设备未连接,无法修改连接设备名称", Toast.LENGTH_SHORT).show();
                Log.e("flag","success设备未连接");
                callbackContext.error("success设备未连接，无法修改连接设备名称");
                return true;
            }


//            mDevice.setDeviceName(args.get(0).toString());
//            Log.e("flag","success setDeviceName设备成功");
//            callbackContext.success("success setDeviceName设备成功");
//            return true;

        }else if (action.equals(conncetDevice)){

            int i = mDevice.connectDevice();
            if (i==0){
                Toast.makeText(cordova.getActivity(), "连接设备成功", Toast.LENGTH_SHORT).show();
                Log.e("flag","success连接设备");
                callbackContext.success("success连接设备");
                return true;
            }else {
                Toast.makeText(cordova.getActivity(), "连接设备失败，错误码"+i, Toast.LENGTH_SHORT).show();
                Log.e("flag","连接设备失败，错误码"+i);
                callbackContext.error("连接设备失败，错误码"+i);
                return true;
            }

        }else if (action.equals(disConnectDevice)){

            cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mDevice.disConnectDevice();
                    Toast.makeText(cordova.getActivity(), "断开设备成功", Toast.LENGTH_SHORT).show();
                    Log.e("flag","断开设备连接成功");
                    callbackContext.success("断开设备连接成功");

                }
            });

            return true;

        }else if (action.equals(readBankCardInfo)){


            mDevice.readBankCardInfo(4, new DeviceCallback() {
                @Override
                public void onSuccess(JSONObject jsonObject) {


                    Message msg = new Message();
                    msg.what = 8;
                    msg.obj = jsonObject.toString();
                    mHandler.sendMessage(msg);

                }

                @Override
                public void onFail(JSONObject jsonObject) {
                    String message= "";
                    try {
                        message = jsonObject.getString("message");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what = 14;
                    msg.obj = message;
                    mHandler.sendMessage(msg);
                }
            },5);


            return true;

        }else if (action.equals(isConnDevice)){

            boolean connDevice = mDevice.isConnDevice();
            if (connDevice){
                Toast.makeText(cordova.getActivity(), "设备已连接", Toast.LENGTH_SHORT).show();
                Log.e("flag","success设备已连接");
                callbackContext.success("success设备已连接");
                return true;

            }else {
                Toast.makeText(cordova.getActivity(), "设备未连接", Toast.LENGTH_SHORT).show();
                Log.e("flag","success设备未连接");
                callbackContext.error("success设备未连接");
                return true;
            }

        } else if (action.equals(readIDCardInfo)){

            mDevice.readIDCardInfo("0", new DeviceCallback() {
                @Override
                public void onSuccess(JSONObject jsonObject) {

                    Message msg = new Message();
                    msg.what = 4;
                    msg.obj = jsonObject;
                    mHandler.sendMessage(msg);


                }

                @Override
                public void onFail(JSONObject jsonObject) {

                    Message msg = new Message();
                    msg.what = 14;
                    msg.obj = jsonObject.toString();
                    mHandler.sendMessage(msg);


                }
            },20);
            return true;

        }else if (action.equals(cancelOperation)){

            mDevice.cancelOperation();
            Toast.makeText(cordova.getActivity(), "取消操作成功", Toast.LENGTH_SHORT).show();
            callbackContext.success("取消操作");
            return true;

        }else if (action.equals(openSignature)){// 打开打开签名屏

            mDevice.openSignatureNew(1240, 860, "",new DeviceCallback() {
                @Override
                public void onSuccess(JSONObject jsonObject) {

//                    try {
//                        String data=jsonObject.getString("data");
//                        callbackContext.success(data);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                    try {
                        String data = jsonObject.getString("data");
                        Message msg = new Message();
                        msg.what = 15;
                        msg.obj = data;
                        mHandler.sendMessage(msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }

                @Override
                public void onFail(JSONObject jsonObject) {

                    Message msg = new Message();
                    msg.what = 14;
                    try {
                        msg.obj = jsonObject.getString("message");

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendMessage(msg);

                }
            });
            return true;
        }
        else if (action.equals(getSignaturePhoto)){//获取 签名信息
            mDevice.getSignaturePhoto(new DeviceCallback() {
                @Override
                public void onSuccess(JSONObject jsonObject) {
                    String data= null;
                    try {
                        data = jsonObject.getString("data");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what = 15;
                    msg.obj = data;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onFail(JSONObject jsonObject) {
                    Message msg = new Message();
                    msg.what = 14;
                    try {
                        msg.obj = jsonObject.getString("message");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendMessage(msg);
                }
            });
            return true;
        }
        else if (action.equals(clearSignature)){

            mDevice.clearSignature(new DeviceCallback() {
                @Override
                public void onSuccess(JSONObject jsonObject) {
                    int data= 0;
                    try {
                        data = jsonObject.getInt("data");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what = 15;
                    msg.obj = data;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onFail(JSONObject jsonObject) {
                    Message msg = new Message();
                    msg.what = 14;
                    try {
                        msg.obj = jsonObject.getString("message");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendMessage(msg);

                }
            });
            return true;

        }
        else if (action.equals(closeSignature)){//关闭签名

            mDevice .closeSignature(new DeviceCallback() {
                @Override
                public void onSuccess(JSONObject jsonObject) {
                    int data= 0;
                    try {
                        data = jsonObject.getInt("data");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what = 15;
                    msg.obj = data;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onFail(JSONObject jsonObject) {
                    Message msg = new Message();
                    msg.what = 14;
                    try {
                        msg.obj = jsonObject.getString("message");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendMessage(msg);
                }
            });
            return true;
        }
        else if (action.equals(readFinger)){//读取指纹
            mDevice.readFinger(new DeviceCallback() {
                @Override
                public void onSuccess(JSONObject jsonObject) {
                    String data= null;
                    try {
                        data = jsonObject.getString("data");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what=1;
                    msg.obj = data;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onFail(JSONObject jsonObject) {
                    String message= null;
                    try {
                        message = jsonObject.getString("message");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what=1;
                    msg.obj = message;
                    mHandler.sendMessage(msg);
                }
            },10);

            return true;
        }
        else if (action.equals(getPublicKey)){

            return true;
        }
        else if (action.equals(loadMainKey)){
            String keyX = "11111111111111111111111111111111";
            String keyY = "00000000000000000000000000000000";
            String algrithm = "21";
            String validate = "82E13665B4624DF5";
            mDevice.loadMainKey(keyX, keyX, validate, 0, "21", new DeviceCallback() {
                @Override
                public void onSuccess(JSONObject jsonObject) {

                    cordova.getActivity().runOnUiThread(
                            new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(cordova.getActivity(), "成功", Toast.LENGTH_SHORT).show();
                                    callbackContext.success("loadMainKey  success");

                                }
                            }
                    );

                }

                @Override
                public void onFail(JSONObject jsonObject) {
                    try {
                        String re = jsonObject.getString("code") + jsonObject.getString("message");
                        cordova.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(cordova.getActivity(), "失败"+re, Toast.LENGTH_SHORT).show();
                                callbackContext.success("loadMainKey  error"+re);
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            },30);
            return true;

        }
        else if (action.equals(loadWorkKey)){

            String keyX = "91171111111111311111111664111111";
            String keyY = "00000000000000000000000000000000";
            String validate = "06EF5B24DA92E320";

            mDevice.loadWorkKey(keyX, keyY, validate
                    , 0, 0, "21", new DeviceCallback() {
                        @Override
                        public void onSuccess(JSONObject jsonObject) {

                            cordova.getActivity().runOnUiThread(
                                    new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(cordova.getActivity(), "成功", Toast.LENGTH_SHORT).show();
                                            callbackContext.success("loadMainKey  success");

                                        }
                                    }
                            );


                        }

                        @Override
                        public void onFail(JSONObject jsonObject) {

                            try {
                                String re = jsonObject.getString("code") + jsonObject.getString("message");
                                cordova.getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(cordova.getActivity(), "失败"+re, Toast.LENGTH_SHORT).show();
                                        callbackContext.success("loadMainKey  error"+re);
                                    }
                                });
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    },30);
            return true;

        } else if (action.equals(readICCardARQC)){//读ARQC信息
            JSONObject jsonObject=new JSONObject();
            try {
                jsonObject.put("P","00");//授权金额
                jsonObject.put("Q","00");//其它金额
                jsonObject.put("R","0156");//交易货币代码 0156 (人民币 CNY )
                jsonObject.put("S","20171211");//交易日期
                jsonObject.put("T","62");//交易类型
                jsonObject.put("U","085811");//交易时间
                jsonObject.put("W","TEST_ABC");//商户名称
            } catch (JSONException e) {
                e.printStackTrace();
            }


            mDevice.readICCardARQC(2, jsonObject.toString(), new DeviceCallback() {
                @Override
                public void onSuccess(JSONObject jsonObject) {

                    String data= null;
                    String cardNo= null;
                    try {
                        data = jsonObject.getString("data");
                        cardNo = jsonObject.getString("cardNo");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what = 3;
                    msg.obj = data+"\r\n"+cardNo;
                    mHandler.sendMessage(msg);


                }

                @Override
                public void onFail(JSONObject jsonObject) {

                    String message= null;
                    try {
                        message = jsonObject.getString("message");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what = 3;
                    msg.obj = message;
                    mHandler.sendMessage(msg);


                }
            },5);

            return true;

        }
        else if (action.equals(validateARPC)){

//            mDevice.validateARPC(4,);
            return true;
        }
        else if (action.equals(getPin)){

            mDevice.getPin(true, 1, 0, "6217231105000876203", "21",
                    new DeviceCallback() {
                        @Override
                        public void onSuccess(JSONObject jsonObject) {

                            int option= 0;
                            try {
                                option = jsonObject.getInt("option");
                                if(option==0){
                                    //String pwd=CHexConver.hexStr2Str(jsonObject.getString("data"));
                                    String pwd = jsonObject.getString("data");
                                    Message msg = new Message();
                                    msg.what = 7;
                                    msg.obj = pwd;
                                    mHandler.sendMessage(msg);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onFail(JSONObject jsonObject) {

                            String message= "";
                            try {
                                message = jsonObject.getString("message");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Message msg = new Message();
                            msg.what = 7;
                            msg.obj = message;
                            mHandler.sendMessage(msg);

                        }
                    },30);
            return true;
        }
//        else {
//            return false;
//        }


        return super.execute(action, args, callbackContext);

    }
}
